跳到主要内容

19 删除链表的倒数第 N 个结点

https://leetcode.cn/leetbook/read/top-interview-questions-easy/xn2925/

https://leetcode.cn/problems/remove-nth-node-from-end-of-list/description/

cost: 13m32s

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* first = head;
ListNode* second = nullptr;
while (first != nullptr) {
first = first->next;
if (n > 0) {
n -= 1;
continue;
}
if (second == nullptr) {
second = head;
} else {
second = second->next;
}
}
if (second == nullptr) {
return head->next;
}
second->next = second->next->next;
return head;
}
};
  • 时间复杂度:O(n)
  • 空间复杂度:O(1)